package com.wencai.test;

import com.wencai.bean.SecondaryIntent;
import com.wencai.bean.Stock;
import com.wencai.bean.WencaiPayload;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangpan
 * @date 2023/7/27
 */
public class WencaiUtils {

    private static String hexin = "Hexin-V";

    private static String url = "https://www.iwencai.com/customized/chart/get-robot-data";

    public static List<Stock> getDailyStock(String date, String question, String range, String hexinValue) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().build();
        RequestBody requestBody = RequestBody.create(JSON.toJSONString(new WencaiPayload(question

                , SecondaryIntent.stock)), MediaType.get("application/json;charset=UTF-8"));
        Request request = new Request.Builder().url(url).method("post", requestBody).addHeader(hexin, hexinValue)
                .build();
        Call call = client.newCall(request);
        Response response = call.execute();
        if (response.code() != 200) {
            throw new RuntimeException();
        }
        String body = response.body().string();
        JSONArray datas = getDatas(body);
        List<Stock> list = new ArrayList<>();

        for (Object obj : datas) {
            JSONObject js = (JSONObject) obj;
            String stockName = js.get("股票简称").toString();
            Number increment = (Number) js.get("竞价涨幅[" + range + "]");
            String code = js.get("code").toString();
            if (code.startsWith("00")) {
                code = "sz." + code;
            } else {
                code = "sh." + code;
            }
            list.add(new Stock(stockName, code, increment.toString(), date));
        }
        return list;
    }

    private static JSONArray getDatas(String body) {
        JSONObject jsonObject = JSON.parseObject(body);
        Object statusCode = jsonObject.get("status_code");
        if (!Integer.valueOf(0).equals(statusCode)) {
            throw new RuntimeException();
        }
        JSONArray data = (JSONArray) ((JSONObject) jsonObject.get("data")).get("answer");
        JSONObject json = (JSONObject) data.get(0);
        JSONObject txt = (JSONObject) ((JSONArray) json.get("txt")).get(0);
        JSONObject content = (JSONObject) txt.get("content");
        JSONArray component = (JSONArray) content.get("components");
        return (JSONArray) ((JSONObject) ((JSONObject) component.get(0)).get("data")).get("datas");
    }
}
